package notInLeetcode;

/**
 * todo
 *
 * @author: luolidong
 * @create: 2021-07-16 20:21
 * @version: 1.0
 */
public class Sqrt {
    /**
    * Java实现开平方的牛顿迭代法. 求的算术平方根就是求 的正根, 得迭代公式: .
     * y = (x + n / x) / 2
    * @Param: [n]
    * @return: double
    */
    public double getSqrt(double n,double d){
        double x=n;
        double y=(x + n / x) / 2;
//        while (Math.abs(x-y)>d){
//            x=y;
//            y=(x + n / x) / 2;
//
//        }
        int c=5;
        while (c>0){
            x=y;
            y=(x + n / x) / 2;
            c--;
        }
        return y;
    }

    public static void main(String[] args) {
        double sqrt = new Sqrt().getSqrt(2, 1e-5);
        System.out.println(sqrt);
        System.out.println(Math.pow(2, 0.5));

    }
}
